package com.george.controller;

import cn.hutool.core.util.ObjectUtil;
import com.george.entity.Result;
import com.george.entity.StatusCode;
import com.george.model.dto.LoginDto;
import com.george.model.entity.Role;
import com.george.model.entity.User;
import com.george.service.IRoleService;
import com.george.service.IUserService;
import com.george.util.JwtUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  用户登录
 * </p>
 *
 * @author GeorgeChan 2019/10/5 22:10
 * @version 1.0
 * @since jdk1.8
 */
@RestController
@CrossOrigin // 跨域
@RefreshScope // 刷新配置
public class LoginController {
    private final IUserService userService;
    private final IRoleService roleService;
    private final JwtUtil jwtUtil;

    @Autowired
    public LoginController(IUserService userService, IRoleService roleService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.roleService = roleService;
        this.jwtUtil = jwtUtil;
    }

    // 生成token的key
    @Value("${jwt.config.key}")
    private String jwtKey;
    // token过期时长（毫秒）
    @Value("${jwt.config.ttl}")
    private int jwtTtl;
    /**
     * 用户登录
     * @param user 登录参数
     * @return 登录结果
     */
    @PostMapping("/api/login")
    public Result login(@RequestBody User user) {
        if (ObjectUtil.isNull(user)) {
            return new Result(false, StatusCode.LOGINERROR, "用户名或密码错误！");
        }
        user = userService.findLoginUser(user.getUsername(), user.getPassword());
        if (ObjectUtil.isNull(user)) {
            return new Result(false, StatusCode.LOGINERROR, "用户名或密码错误！");
        }
        // 创建token
        jwtUtil.setTtl(jwtTtl);
        jwtUtil.setKey(jwtKey);
        String token = jwtUtil.createJWT(String.valueOf(user.getId()), user.getUsername(), "root");
        LoginDto loginDto = new LoginDto();
        loginDto.setUser(user);
        loginDto.setAuthorization(token);
        return new Result(true, StatusCode.OK, "登录成功！", loginDto);
    }
}
